package com.offlineanswer;

import android.accessibilityservice.AccessibilityService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MyAccessibility extends AccessibilityService {
    public static MyAccessibility mService;
    public static List<String> answers=new ArrayList<>();
    private int min=60,max=100;
    private String question="";
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        mService=this;
        min = Integer.parseInt(App.sp.getString("min","60"));
        max = Integer.parseInt(App.sp.getString("max","100"));

    }
    @Override
    public void onInterrupt() {
        mService=null;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mService=null;
    }
    public static boolean isStart() {
        return mService != null;
    }
    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        if (accessibilityEvent.getClassName().toString().endsWith("com.ts.zlzs.ui.offline.OfflineDeptDetailsActivity")) {
            new android.os.Handler().postDelayed(this::queryUrls, 3000);
        }
    }
    public void queryUrls() {
        AccessibilityNodeInfo root = getRootInActiveWindow();
        List<AccessibilityNodeInfo> list = root.findAccessibilityNodeInfosByViewId("com.ts.zlzs:id/act_offline_dept_details_tvContent");
        if (list.size()==0){
            showToast("请回到答题界面");
            return;
        };
        question = list.get(0).getText().toString();
        question = question.substring(question.lastIndexOf("】") + 1);
        showToast("搜索中，请稍候");
        answers.clear();

        if (App.sp.getBoolean("query1", true)){
            showToast("引擎1开始搜索");
            query1(question);
        }else {
            if (App.sp.getBoolean("query2", false)) {
                showToast("引擎2开始搜索");
                query2(question);
            } else {
                if (App.sp.getBoolean("query3", false)) {
                    showToast("引擎3开始搜索");
                    query3(question);
                } else {
                    if (App.sp.getBoolean("query4", false)) {
                        showToast("引擎4开始搜索");
                        query4(question);
                    } else {
                        if (App.sp.getBoolean("query5", false)) {
                            showToast("引擎5开始搜索");
                            query5(question);
                        } else {
                            if (answers.size() > 0) inputText(answers.get(0));
                            showToast("搜索完毕");
                        }
                    }
                }
            }
        }
    }
    public void query5(String question) {
        try {
            Elements list = Jsoup.connect("https://www.xinglinpukang.com/search/" + question + "/?type=audio").get().getElementsByAttributeValueContaining("href", "/audio/");
            if (list.size()==0){
                addCallback("","query5",0,0);
                return;
            }
            for (int i = 0; i < list.size(); i++) {
                addCallback(Jsoup.connect("https://www.xinglinpukang.com" + list.get(i).attr("href")).get().getElementsByClass("txt_1").text(),"query5",i+1,list.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void query4(String question) {
        try {
            Elements list = Jsoup.connect("http://so.39.net/search/wd?words="+question).get().getElementsByAttributeValueContaining("href", "http://ask.39.net/question");
            if (list.size()==0){
                addCallback("","query4",0,0);
                return;
            }
            for (int i = 0; i < list.size(); i++) {
                addCallback(Jsoup.connect(list.get(i).attr("href")).get().getElementsByClass("sele_txt").text(),"query4",i+1,list.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void query3(String question) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Elements list = Jsoup.connect("http://so.120ask.com/?kw=" + question).get().getElementById("datalist").getElementsByAttributeValueContaining("href", "https://www.120ask.com/question");
                  if (list.size()==0){
                      addCallback("","query3",0,0);
                      return;
                  }
                    for (int i = 0; i < list.size(); i++) {
                        addCallback(Jsoup.connect(list.get(i).attr("href")).get().getElementsByClass("b_anscont_cont").text(),"query3",i+1,list.size());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void query2(String question) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Elements list = Jsoup.connect("http://so.39.net/search/wd?words=" + question).get().getElementsByAttributeValueContaining("href", "ask.39.net/question");
                    if (list.size()==0){
                        addCallback("","query2",0,0);
                        return;
                    }
                    for (int i = 0; i < list.size(); i++) {
                        addCallback(Jsoup.connect(list.get(i).attr("href")).get().getElementsByClass("sele_txt").text(),"query2",i+1,list.size());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void query1(String finalQuestion) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Elements list = Objects.requireNonNull(Jsoup.connect("http://so.xywy.com/comse.php?keyword=" + finalQuestion + "&src=so").get().getElementsByAttributeValueContaining("href","club.xywy.com/question/"));
                    if (list.size()==0){
                        addCallback("","query1",0,0);
                        return;
                    }
                    for (int i = 0; i < list.size(); i++) {
                        Element element = list.get(i);
                        String url = element.getElementsContainingText("详情").attr("href");
                        if (!url.equals("")){
                            addCallback(Jsoup.connect(url).get().getElementsByClass("pt15 f14 graydeep  pl20 pr20 deepblue").text(),"query1",i+1,list.size());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    public void addCallback(String t,String engine,int now,int all){
        answers.add(t);
        if (now==all){
            boolean query2 = App.sp.getBoolean("query2", false);
            boolean query3 = App.sp.getBoolean("query3", false);
            boolean query4 = App.sp.getBoolean("query4", false);
            boolean query5 = App.sp.getBoolean("query5", false);
            switch (engine) {
                case "query1":
                    if (query2) {
                        showToast("引擎2开始搜索");
                        query2(question);
                    } else {
                        if (query3) {
                            showToast("引擎3开始搜索");
                            query3(question);
                        } else {
                            if (query4) {
                                showToast("引擎4开始搜索");
                                query4(question);
                            } else {
                                if (query5) {
                                    showToast("引擎5开始搜索");
                                    query5(question);
                                } else {
                                    if (answers.size() > 0) inputText(answers.get(0));
                                    showToast("搜索完毕");
                                }
                            }
                        }
                    }
                    break;
                case "query2":
                    if (query3) {
                        showToast("引擎3开始搜索");
                        query3(question);
                    } else {
                        if (query4) {
                            showToast("引擎4开始搜索");
                            query4(question);
                        } else {
                            if (query5) {
                                showToast("引擎5开始搜索");
                                query5(question);
                            } else {
                                if (answers.size() > 0) inputText(answers.get(0));
                                showToast("搜索完毕");
                            }
                        }
                    }
                    break;
                case "query3":
                    if (query4) {
                        showToast("引擎4开始搜索");
                        query4(question);
                    } else {
                        if (query5) {
                            showToast("引擎5开始搜索");
                            query5(question);
                        } else {
                            if (answers.size() > 0) inputText(answers.get(0));
                            showToast("搜索完毕");
                        }
                    }
                    break;
                case "query4":
                    if (query5) {
                        showToast("引擎5开始搜索");
                        query5(question);
                    } else {
                        if (answers.size() > 0) inputText(answers.get(0));
                        showToast("搜索完毕");
                    }
                    break;
                case "query5":
                    if (answers.size() > 0) inputText(answers.get(0));
                    showToast("搜索完毕");
                    break;
            }
        }
    }
    public static int count(String text) {
        int result=0;
        for(int i=0;i<text.length();i++){
            String b=Character.toString(text.charAt(i));
            if(b.matches("^[\u4e00-\u9fa5]{1}$"))result++;
        }
        return result;
    }
    public void inputText(String text){
        AccessibilityNodeInfo root = getRootInActiveWindow();
        List<AccessibilityNodeInfo> edittext = root.findAccessibilityNodeInfosByViewId("com.ts.zlzs:id/offline_more_details_tvAnalysisGuide");
        if (edittext.size()==0){
            showToast("请回到答题界面");
            return;
        }
        Bundle arguments = new Bundle();
        arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
        edittext.get(0).performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
    }
    public void switchAnswer() {
        if (answers.size()==0){
            showToast("没有搜索到结果");
        }else {
            int a=(int) (Math.random() * answers.size());
            showToast(a+"/"+answers.size());
            inputText(answers.get(a));
        }
    }

    private void showToast(String s) {
        new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(getApplicationContext() ,s,Toast.LENGTH_SHORT).show());
    }

    public void submit() {
        AccessibilityNodeInfo root = getRootInActiveWindow();
        List<AccessibilityNodeInfo> bt = root.findAccessibilityNodeInfosByViewId("com.ts.zlzs:id/act_offline_dept_details_tvSubmit");
       if (bt.size()!=0){
           bt.get(0).performAction(16);
       }else {
           showToast("请回到答题界面");
       }
    }
    public void pass() {
        AccessibilityNodeInfo root = getRootInActiveWindow();
        List<AccessibilityNodeInfo> bt = root.findAccessibilityNodeInfosByViewId("com.ts.zlzs:id/act_offline_dept_details_tvNextQuestion");
        if (bt.size()!=0){
            bt.get(0).performAction(16);
        }else {
            showToast("请回到答题界面");
        }
    }
}
